﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace WSManager.Model
{
    public static class ModelRepairer
    {
        /// <summary>
        /// Repairs category
        /// </summary>
        /// <param name="item">item to repair - will not be copied</param>
        /// <returns>the same item that is on input</returns>
        public static Category Repair(this Category item)
        {
            if (string.IsNullOrEmpty(item.Name) && !string.IsNullOrEmpty(item.Id)) item.Name = Uri.UnescapeDataString(item.Id);
            if (!string.IsNullOrEmpty(item.Name) && string.IsNullOrEmpty(item.Id)) item.Id = Uri.EscapeDataString(item.Name);
            if (item.Subcategories == null) item.Subcategories = new List<Category>();
            item.Description = item.Description ?? string.Empty;
            return item;
        }

        public static Article Repair(this Article item)
        {
            item.Metadata = item.Metadata ?? new Dictionary<string, string>();
            item.Categories = item.Categories ?? new List<Category>();
            item.Content = item.Content ?? new XElement("content");
            item.Description = item.Description ?? string.Empty;
            return item;
        }

        public static Web Repair(this Web item)
        {
            item.Articles = item.Articles ?? new Article[0];
            item.Categories = item.Categories ?? new Category[0];
            item.Files = item.Files ?? new WebFile[0];
            item.Images = item.Images ?? new WebImage[0];
            item.Metadata = item.Metadata ?? new WebMetadata();
            item.Metadata.Repair();

            foreach (var category in item.Categories)
                category.Repair();
            foreach (var article in item.Articles)
                article.Repair();
            foreach (var webImage in item.Images)
                webImage.Repair();
            foreach (var webFile in item.Files)
                webFile.Repair();
            return item;
        }

        public static WebImage Repair(this WebImage item)
        {
            return item;
        }

        public static WebFile Repair(this WebFile item)
        {
            return item;
        }

        public static WebMetadata Repair(this WebMetadata item)
        {
            item.ArticleMetadataDefinition = item.ArticleMetadataDefinition ??
                                             new List<StringVariables.VariableDefinition>();
            return item;
        }
    }
}
